package app.qrcode.browser.ykpixabay.ui.settings

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import app.qrcode.browser.ykpixabay.R
import app.qrcode.browser.ykpixabay.logic.dao.KeyDao
import kotlinx.android.synthetic.main.fragment_settings_not_login.*

/**
 * Created by YiGo on 2022/4/21.
 */
class SettingsNotLoginFragment : Fragment() {
    val viewModel by lazy { ViewModelProvider(this).get(SettingsNotLoginViewModel::class.java) }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_settings_not_login, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val controller =
            Navigation.findNavController(this.requireActivity(), R.id.fragmentContainerView)
        if (KeyDao.isKeySaved()) {
            viewModel.setChangedBtnText(KeyDao.getKey().toString())
            viewModel.setBtnText("修改")
        } else {
            viewModel.setChangedBtnText("尚未添加卡密")
            viewModel.setBtnText("添加")
        }
        viewModel.btnText.observe(viewLifecycleOwner) { text ->
            button_change_key_not.text = text
        }
        viewModel.changedBtnText.observe(viewLifecycleOwner) { text ->
            textView_pixabay_key_content_not.text = text
        }
        button_change_key_not.setOnClickListener {
            controller.navigate(R.id.action_settingsNotLoginFragment_to_enterKeyFragment)
        }
        if (!KeyDao.isKeySaved()) {
            button_clear_key_not.isEnabled = false
        }

        button_clear_key_not.setOnClickListener {
            //弹出消息框
            AlertDialog.Builder(this.requireContext()).apply {
                setTitle("你确定要清除卡密吗")
                setPositiveButton(
                    "确定"
                ) { _, _ ->
                    KeyDao.deleteKey()
                    viewModel.setChangedBtnText("尚未添加卡密")
                    viewModel.setBtnText("添加")
                }
                setNegativeButton(
                    "取消"
                ) { _, _ ->

                }
            }.create().show()
        }
    }
    }

